package io.rong.app.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.yunshipei.base.BaseActivity;
import com.yunshipei.common.Globals;
import com.yunshipei.common.wedigt.YspTitleBar;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.ClearGroupNumber;
import com.yunshipei.model.EventModelObject;
import com.yunshipei.ui.activity.CompanyNameLoginActivity;
import com.yunshipei.ui.activity.MainActivity;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import io.rong.app.DemoContext;
import io.rong.app.RongCloudEvent;
import io.rong.app.fragment.FriendMultiChoiceFragment;
import io.rong.app.model.GroupCreateInfo;
import io.rong.app.model.RongConst;
import io.rong.app.ui.LoadingDialog;
import io.rong.app.utils.Constants;
import io.rong.app.utils.StringUtilSub;
import io.rong.eventbus.EventBus;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imkit.fragment.SubConversationListFragment;
import io.rong.imkit.mention.RongMentionManager;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;

/**
 * Created by Bob on 2015/3/27.
 * 通过intent获得发送过来的数据
 * 1，程序切到后台，点击通知栏进入程序
 * 2，收到 push 消息（push消息可以理解为推送消息）
 */
public class DemoActivity extends BaseActivity implements Handler.Callback, View.OnClickListener {
    private static final String TAG = DemoActivity.class.getSimpleName();
    //    对方id
    private String targetId;
    //    刚刚创建完讨论组后获得讨论组的targetIds
    private String targetIds;
    //    讨论组id
    private YspTitleBar mTitleBar;
    private String tag = null;
    //    会话类型
    private Conversation.ConversationType mConversationType;
    private LoadingDialog mDialog;
    private Handler mHandler;
    private ImageView groupDetail;
    public static final int REQUEST_CODE = 1;
    private boolean notificationState = false;    //默认为false为非notification消息
    private boolean notificationWhere = false;
    private SharedPreferences mySharePreferences = null;
    private SharedPreferences.Editor editor = null;
    private Map<String, io.rong.imlib.model.UserInfo> atMap = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.de_activity);
        mySharePreferences = getSharedPreferences("ysp_rongCloud", Activity.MODE_PRIVATE);
        editor = mySharePreferences.edit();
        initView();
        initData();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        initAtData();
    }

    protected void initView() {
        editor.putBoolean("ConversationState", false);
        editor.commit();
        mTitleBar = (YspTitleBar) findViewById(R.id.title_bar);
        mHandler = new Handler(this);
        groupDetail = (ImageView) findViewById(R.id.group_detail);
        groupDetail.setOnClickListener(this);
        Intent intent = getIntent();
        notificationState = intent.getBooleanExtra(Globals.NOTIFICATIONSTATE, false);
        notificationWhere = intent.getBooleanExtra(Globals.NOTIFICATIONWHERE, false);
        if (intent != null && intent.hasExtra("DEMO_COVERSATIONTYPE")
                && intent.hasExtra("DEMO_TARGETID")
                && intent.hasExtra("DEMO_COVERSATION")) {
            if (DemoContext.getInstance(DemoActivity.this) != null) {
                String conversation = intent.getStringExtra("DEMO_COVERSATION");
                targetId = intent.getStringExtra("DEMO_TARGETID");
                String conversationType = intent
                        .getStringExtra("DEMO_COVERSATIONTYPE");
                openConversationFragment(conversation, targetId,
                        conversationType);
            }
        }
        //push或通知过来
        if (intent != null && intent.getData() != null && intent.getData().getScheme().equals("rong") && intent.getData().getQueryParameter("push") != null) {
            //通过intent.getData().getQueryParameter("push") 为true，判断是否是push消息
            if (DemoContext.getInstance(DemoActivity.this) != null && intent.getData().getQueryParameter("push").equals("true")) {
                enterActivity(intent);
            } else {
                enterFragment(intent);
            }
        } else if (intent != null) {
            //程序切到后台，收到消息后点击进入,会执行这里
            if (RongIM.getInstance() == null) {
                reconnect();
            } else if (RongIM.getInstance().getCurrentConnectionStatus().equals(
                    RongIMClient.ConnectionStatusListener.ConnectionStatus.DISCONNECTED)) {
                reconnect();
            } else {
                enterFragment(intent);
            }
        }

        mTitleBar.setBackClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backStateHandler();
            }
        });

        mTitleBar.setSubTitleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backStateHandler();
            }
        });

    }

    private void initAtData() {
        RongIM.getInstance().setGroupMembersProvider(new RongIM.IGroupMembersProvider() {
            @Override
            public void getGroupMembers(String groupId, RongIM.IGroupMemberCallback callback) {
                DatabaseUtil util = new DatabaseUtil();
                List<io.rong.imlib.model.UserInfo> list = new ArrayList<>();
                GroupCreateInfo groupCreateInfo = util.findGroupById(groupId);
                if (!TextUtils.isEmpty(groupCreateInfo.getGourpMembers())) {
                    JSONArray uuids = null;
                    try {
                        uuids = new JSONArray(groupCreateInfo.getGourpMembers());
                        for (int i = 0; i < uuids.length(); i++) {
                            list.add(util.queryByUuid(uuids.optString(i, "")));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                callback.onGetGroupMembersResult(list);
            }
        });
    }

    private void reconnect() {
        SharedPreferences sSharedPreferences = getSharedPreferences("ysp_rongCloud", Activity.MODE_PRIVATE);
        if (sSharedPreferences != null) {
            String token = sSharedPreferences.getString("TOKEN", "defult");
            reconnect(token);
        } else {
            Log.e("reconnect", "token is null");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 收到 push 以后，打开会话页面
     *
     * @param conversation
     * @param targetId
     * @param conversationType
     */
    private void openConversationFragment(String conversation, String targetId, String conversationType) {
        String tag;
        if (conversation.equals("conversation")) {
            tag = "conversation";
            ConversationFragment conversationFragment = new ConversationFragment();
            Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                    .appendPath("conversation").appendPath(conversationType.toLowerCase())
                    .appendQueryParameter("targetId", targetId).build();
            conversationFragment.setUri(uri);
            mConversationType = Conversation.ConversationType.valueOf(conversationType);
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.de_content, conversationFragment, tag);
            transaction.addToBackStack(null).commitAllowingStateLoss();
        }
    }

    /**
     * 收到 push 消息后，选择进入哪个 Activity
     * 如果程序缓存未被清理，进入 MainActivity
     * 程序缓存被清理，重新获取token
     * <p>
     * 作用：由于在 manifest 中 intent-filter 是配置在 DemoActivity 下面，所以收到消息后点击notifacition 会跳转到 DemoActivity。
     * 以跳到 MainActivity 为例：
     * 在 DemoActivity 收到消息后，选择进入 MainActivity，这样就把 MainActivity 激活了，当你读完收到的消息点击 返回键 时，程序会退到
     * MainActivity 页面，而不是直接退回到 桌面。
     */
    private void enterActivity(Intent intent) {
        if (DemoContext.getInstance(DemoActivity.this) != null) {
            String token = DemoContext.getInstance(DemoActivity.this).getSharedPreferences().getString("DEMO_TOKEN", "defult");
            Intent in = new Intent();
            if (!token.equals("defult")) {
                in.setClass(DemoActivity.this, MainActivity.class);
                in.putExtra("PUSH_TOKEN", token);
                in.putExtra("PUSH_INTENT", intent.getData());
            } else {
                in.setClass(DemoActivity.this, CompanyNameLoginActivity.class);
                in.putExtra("PUSH_CONTEXT", "push");
            }
            startActivity(in);
            finish();
        }
    }

    /**
     * 收到push消息后做重连，重新连接融云
     *
     * @param token
     */
    private void reconnect(String token) {
        mDialog = new LoadingDialog(this);
        mDialog.setCancelable(false);
        mDialog.setText("connect_auto_reconnect");
        mDialog.show();
        try {
            RongIM.connect(token, new RongIMClient.ConnectCallback() {

                @Override
                public void onTokenIncorrect() {

                }

                @Override
                public void onSuccess(String userId) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mDialog.dismiss();
                            Intent intent = getIntent();
                            if (intent != null) {
                                enterFragment(intent);
                            }
                        }
                    });
                }

                @Override
                public void onError(RongIMClient.ErrorCode e) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mDialog.dismiss();
                        }
                    });
                }
            });

        } catch (Exception e) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mDialog.dismiss();
                }
            });
            e.printStackTrace();
        }

    }

    /**
     * 消息分发，选择跳转到哪个fragment
     *
     * @param intent
     */
    private void enterFragment(Intent intent) {
        String tag = null;
        if (intent != null) {
            Fragment fragment = null;
            if (intent.getExtras() != null && intent.getExtras().containsKey(RongConst.EXTRA.CONTENT)) {
                String fragmentName = intent.getExtras().getString(RongConst.EXTRA.CONTENT);
                fragment = Fragment.instantiate(this, fragmentName);
            } else if (intent.getData() != null) {
                if (intent.getData().getPathSegments().get(0).equals("conversation")) {
                    /**
                     * 在此添加是否进入聊天界面状态标示
                     */
                    editor.putBoolean("ConversationState", false);
                    editor.commit();
                    tag = "conversation";
                    if (intent.getData().getLastPathSegment().equals("system")) {
                        //注释掉的代码为不加输入框的聊天页面（此处作为示例）
//                        String fragmentName = MessageListFragment.class.getCanonicalName();
                        String fragmentName = "";
                        fragment = Fragment.instantiate(this, fragmentName);
                        startActivity(new Intent(DemoActivity.this, NewFriendListActivity.class));
                        finish();
                        List<Conversation> conversations = RongIM.getInstance().getRongIMClient().getConversationList(Conversation.ConversationType.SYSTEM);
                        for (int i = 0; i < conversations.size(); i++) {
                            RongIM.getInstance().getRongIMClient().clearMessagesUnreadStatus(Conversation.ConversationType.SYSTEM, conversations.get(i).getSenderUserId());
                        }
                    } else {
                        setTitle(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()),
                                intent.getData().getQueryParameter("targetId"));
                        targetId = intent.getData().getQueryParameter("targetId");
                        openConversationFragment("conversation", intent.getData().getQueryParameter("targetId"), intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
                        return;
                    }
                } else if (intent.getData().getLastPathSegment().equals("conversationlist")) {
                    tag = "conversationlist";
                    String fragmentName = ConversationListFragment.class.getCanonicalName();
                    fragment = Fragment.instantiate(this, fragmentName);
                } else if (intent.getData().getLastPathSegment().equals("subconversationlist")) {
                    tag = "subconversationlist";
                    String fragmentName = SubConversationListFragment.class.getCanonicalName();
                    fragment = Fragment.instantiate(this, fragmentName);
                } else if (intent.getData().getPathSegments().get(0).equals("friend")) {
                    tag = "friend";
                    String fragmentName = FriendMultiChoiceFragment.class.getCanonicalName();
                    fragment = Fragment.instantiate(this, fragmentName);
                }
                targetId = intent.getData().getQueryParameter("targetId");
                targetIds = intent.getData().getQueryParameter("targetIds");
                if (targetId != null) {
                    intent.getData().getLastPathSegment();//获得当前会话类型
                    mConversationType = Conversation.ConversationType.valueOf(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
                } else if (targetIds != null)
                    mConversationType = Conversation.ConversationType.valueOf(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
            }

            if (fragment != null) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.add(R.id.de_content, fragment, tag);
                transaction.addToBackStack(null).commitAllowingStateLoss();
            }
        }
    }

    private void setTitle(String type, String mTargetId) {
        targetId = mTargetId;
        if (type != null) {
            if (type.equals(String.valueOf(Conversation.ConversationType.PRIVATE))) {
                io.rong.imlib.model.UserInfo userInfo = new DatabaseUtil().queryByUuid(mTargetId);
                String name = "";
                if (userInfo != null) {
                    name = userInfo.getName();
                    mTitleBar.setTitle(name);
                }
            } else if (type.equals(String.valueOf(Conversation.ConversationType.GROUP))) {
                if (!TextUtils.isEmpty(mTargetId)) {
                    Group group = RongCloudEvent.getInstance().getGroupInfo(mTargetId);
                    if (group != null) {
                        String groupName = group.getName();
                        mTitleBar.setTitle(StringUtilSub.getInstance().SubStringAddCH(0, groupName, 6));
                        groupDetail.setVisibility(View.VISIBLE);
                    } else {
                        Log.e("setTitle", "group is null");
                    }
                }
            }
        }
    }

    /**
     * 设置 title
     */
    protected void initData() {
        atMap = new HashMap<>();
        if (mConversationType != null) {
            if (mConversationType.equals(Conversation.ConversationType.PRIVATE)) {
                if (DemoContext.getInstance(DemoActivity.this) != null) {
                    //单聊时初始化数据
                    io.rong.imlib.model.UserInfo rongUserInfo = new DatabaseUtil().queryByUuid(targetId);
                    String name = "";
                    if (rongUserInfo != null) {
                        name = rongUserInfo.getName();
                        mTitleBar.setTitle(name);
                    } else {
                        Log.e("demo title", "name 为空");
                    }
                }
            } else if (mConversationType.equals(Conversation.ConversationType.GROUP)) {
                if (DemoContext.getInstance(DemoActivity.this) != null) {
                    /**
                     * int location insert codes about groupTitle
                     * 获取群组名称,设置群组标题
                     */
                    if (!TextUtils.isEmpty(targetId)) {
                        Group group = RongCloudEvent.getInstance().getGroupInfo(targetId);
                        if (group != null) {
                            String groupName = group.getName();
                            mTitleBar.setTitle(StringUtilSub.getInstance().SubStringAddCH(0, groupName, 6));
                            groupDetail.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        tag = null;
        Fragment fragment = null;
        if (intent.getExtras() != null && intent.getExtras().containsKey(RongConst.EXTRA.CONTENT)) {
            String fragmentName = intent.getExtras().getString(RongConst.EXTRA.CONTENT);
            fragment = Fragment.instantiate(this, fragmentName);
        } else if (intent.getData() != null) {

            if (intent.getData().getPathSegments().get(0).equals("conversation")) {
                tag = "conversation";
                fragment = getSupportFragmentManager().findFragmentByTag(tag);
                if (fragment != null)
                    return;
                String fragmentName = ConversationFragment.class.getCanonicalName();
                fragment = Fragment.instantiate(this, fragmentName);
            } else if (intent.getData().getLastPathSegment().equals("conversationlist")) {
                tag = "conversationlist";
                String fragmentName = ConversationListFragment.class.getCanonicalName();
                fragment = Fragment.instantiate(this, fragmentName);
            } else if (intent.getData().getLastPathSegment().equals("subconversationlist")) {
                tag = "subconversationlist";
                String fragmentName = SubConversationListFragment.class.getCanonicalName();
                fragment = Fragment.instantiate(this, fragmentName);
            }
        }
        if (fragment != null) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.de_content, fragment, tag);
            transaction.addToBackStack(null).commitAllowingStateLoss();
        }
    }


    @Override
    public boolean handleMessage(Message msg) {
        return false;
    }

    /**
     * 返回按钮
     */
    public void backStateHandler() {
        if (!notificationState && !notificationWhere) {
            finish();
        } else {
            Intent intent = new Intent();
            intent.setClass(DemoActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
        if (fragment != null) {
            FragmentManager fm = getSupportFragmentManager();
            fm.beginTransaction().remove(fragment).commit();
            fm.executePendingTransactions();
        }
        editor.putBoolean("ConversationState", true);
        editor.commit();
        if (DemoActivity.this.getCurrentFocus() != null)
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                    DemoActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.group_detail:
                //群组详情信息
                GroupCreateInfo newGroupCreateInfo = DemoContext.getInstance(DemoActivity.this).getOneResult(targetId);
                if (newGroupCreateInfo != null) {
                    Uri uri = Uri.parse("demo://" + getApplicationInfo().packageName).buildUpon().appendPath("conversationSetting")
                            .appendPath(String.valueOf(Conversation.ConversationType.GROUP)).appendQueryParameter("targetId", newGroupCreateInfo.getId()).build();
                    Intent intent = new Intent(this, GroupMainPageActivity.class);
                    intent.putExtra("INTENT_GROUP", newGroupCreateInfo);
                    intent.setData(uri);
                    startActivityForResult(intent, REQUEST_CODE);
                } else {
                    Toast.makeText(DemoActivity.this, "信息有误，请重新登录后查看", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && resultCode == Constants.GROUP_QUIT_REQUESTCODE) {
            this.finish();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void onEventMainThread(EventModelObject i) {
        mTitleBar.setTitle(StringUtilSub.getInstance().SubStringAddCH(0, i.getMassage(), 6));
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing())
            RongMentionManager.getInstance().destroyInstance(mConversationType, targetId);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            backStateHandler();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void onEventMainThread(ClearGroupNumber clearGroupNumber) {
        finish();
        Toast.makeText(this, "您已被群主移出群组", Toast.LENGTH_SHORT).show();
    }

}

